package com.example.reserveseat.GateWay;

import com.alibaba.fastjson.JSON;
import com.example.reserveseat.Enums.ResponseStatusEnum;
import com.example.reserveseat.Factory.ScheduledFactory;
import com.example.reserveseat.Object.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;

/**
 * @author lyf
 * @date 2024/7/20 3:57
 */
@Component
@Slf4j
public class ScheduledGateWay {

    @Value("${yuqian.token}")
    private String token;
    @Value("${OneSing}")
    private String sign1;

    @Value("${TwoSing}")
    private String sign2;

    @Value("${threeSign}")
    private String sign3;

    @Value("${yuqian.sign}")
    private String sign;


    public ReservationResponse queryInfo(String areaId,LocalDate chooseDate) {
        String urlString = "https://study.nslib.cn/appapi/ns/reservation/Seats";

        try {
            // 创建URL对象
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Token", token);
            String sign="";
            if(areaId.equals("1")){
                sign=sign1;
            }
            if(areaId.equals("2")){
                sign=sign2;
            }
            if(areaId.equals("3")){
                sign=sign3;
            }
            connection.setRequestProperty("Sign", sign);
            ScheduledFactory.setRequestHeader(connection);

            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 需要URL编码请求体参数
            String query = "org_id=1&area_id="+areaId+"&choose_date=" + chooseDate;
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = query.getBytes("UTF-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder resString = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    resString.append(line);
                }
                ReservationResponse reservationResponse = JSON.parseObject(resString.toString(), ReservationResponse.class);
                if(reservationResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                    return reservationResponse;
                }
                throw new RuntimeException("调用查询信息失败");
            }

            // 断开连接
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public ListResponse getList(int type,String sign) {
        String urlString = "https://study.nslib.cn/appapi/WXOpenTemplate/List";
        try {
            // 创建URL对象
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Host", "study.nslib.cn");
            connection.setRequestProperty("access_source", "");
            connection.setRequestProperty("instid", "1570");
            connection.setRequestProperty("xweb_xhr", "1");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b13)XWEB/9185");
            connection.setRequestProperty("Token", token);
            connection.setRequestProperty("Sign", sign);
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Referer", "https://servicewechat.com/wx839adc01def5e06c/85/page-frame.html");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

            // 发送POST请求的数据
            String postData = "instid=1570&template_type="+type;
            byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
            connection.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postDataBytes);
                wr.flush();
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                ListResponse listResponse = JSON.parseObject(response.toString(), ListResponse.class);
                if(listResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                    return listResponse;
                }
                throw new RuntimeException("调用getList查询信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 点击确认预约时调用此方法
     * @param orderInfo
     * @return
     */
    public PreOrderResponse preOrder(OrderInfo orderInfo) {
        log.info("入参orderInfo{}",orderInfo.toString());
//        String urlString = "https://study.nslib.cn/appapi/ns/reservation/PreOrder";
//
//        try {
//            // 创建URL对象
//            URL url = new URL(urlString);
//            // 打开连接
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            // 设置请求方法
//            connection.setRequestMethod("POST");
//            connection.setRequestProperty("Token", token);
//            connection.setRequestProperty("Sign", sign);
//            ScheduledFactory.setRequestHeader(connection);
//
//            // 发送POST请求必须设置
//            connection.setDoOutput(true);
//
//            // 需要URL编码请求体参数
//            String query = "org_id=1&area_id="+orderInfo.getAreaId()+"&seat_id="+orderInfo.getSeatId()+"&start_time="+orderInfo.getStartTime()+"&end_time="+orderInfo.getEndTime();
//            try(OutputStream os = connection.getOutputStream()) {
//                byte[] input = query.getBytes("UTF-8");
//                os.write(input, 0, input.length);
//            }
//
//            // 读取响应
//            try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
//                StringBuilder resString = new StringBuilder();
//                String line;
//                while ((line = reader.readLine()) != null) {
//                    resString.append(line);
//                }
//                log.info("点击预约按钮请求响应结果{}",resString);
//                PreOrderResponse preOrderResponse = JSON.parseObject(resString.toString(), PreOrderResponse.class);
//                if(preOrderResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
//                    return preOrderResponse;
//                }
//                throw new RuntimeException("调用preOrder接口查询信息失败");
//            }
//
//            // 断开连接
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
        String urlString = "https://study.nslib.cn/appapi/ns/reservation/PreOrder";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 表示需要发送请求体

            // 设置请求头
            connection.setRequestProperty("Host", "study.nslib.cn");
            connection.setRequestProperty("access_source", "");
            connection.setRequestProperty("instid", "1570");
            connection.setRequestProperty("xweb_xhr", "1");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b13)XWEB/9185");
            connection.setRequestProperty("Token", token);
            connection.setRequestProperty("Sign", "6A61CA338D4C856C450D7745D43D3EC9");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Referer", "https://servicewechat.com/wx839adc01def5e06c/85/page-frame.html");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

            // 发送请求体
            String postData = "org_id=1&area_id="+orderInfo.getAreaId()+"&seat_id="+orderInfo.getSeatId()+"&start_time="+orderInfo.getStartTime()+"&end_time="+orderInfo.getEndTime();
            byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postDataBytes);
                wr.flush();
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                log.info("点击预约按钮请求响应结果{}",response);
                PreOrderResponse preOrderResponse = JSON.parseObject(response.toString(), PreOrderResponse.class);
                if(preOrderResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                    return preOrderResponse;
                }
                throw new RuntimeException("调用preOrder接口查询信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public MemberInfoResponse getMemberInfo(){
        try {
            String urlString = "https://study.nslib.cn/appapi/ns/member/GetMemberInfo";
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 表示需要发送请求体

            // 设置请求头
            connection.setRequestProperty("Host", "study.nslib.cn");
            connection.setRequestProperty("access_source", "");
            connection.setRequestProperty("instid", "1570");
            connection.setRequestProperty("xweb_xhr", "1");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b13)XWEB/9185");
            connection.setRequestProperty("Token", token);
            connection.setRequestProperty("Sign", "6FB0C5479DDB3C1E19A6D8C900A4E58B");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Referer", "https://servicewechat.com/wx839adc01def5e06c/85/page-frame.html");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

            // 发送请求体
            String postData = "from=WXMIN";
            byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postDataBytes);
                wr.flush();
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                log.info("获取紧急联系人接口响应结果{}",response);
                MemberInfoResponse memberInfoResponse = JSON.parseObject(response.toString(), MemberInfoResponse.class);
                if(memberInfoResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                    return memberInfoResponse;
                }
                throw new RuntimeException("调用memberInfo接口查询信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public GenerateOrderResponse generateOrder(OrderInfo orderInfo, List<String> templateIds) {
        log.info("入参orderInfo{},templateIds:{}",orderInfo.toString(),templateIds);
        List<String> data = new ArrayList<>();
        for (String templateId : templateIds) {
            data.add(String.format("\"%s\"", templateId));
        }
        System.out.println(data);
        String urlString = "https://study.nslib.cn/appapi/ns/reservation/GenerateOrder";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 表示需要发送请求体

            // 设置请求头
            connection.setRequestProperty("Host", "study.nslib.cn");
            connection.setRequestProperty("access_source", "");
            connection.setRequestProperty("instid", "1570");
            connection.setRequestProperty("xweb_xhr", "1");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b13)XWEB/9185");
            connection.setRequestProperty("Token", token);
            connection.setRequestProperty("Sign", "39F5CEB9F131151BD74B9DA354F2D4FE");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Referer", "https://servicewechat.com/wx839adc01def5e06c/85/page-frame.html");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

            // 发送请求体
            String postData = "org_id=1&area_id="+orderInfo.getAreaId()+"&seat_id="+orderInfo.getSeatId()+"&start_time="+orderInfo.getStartTime()+"&end_time="+orderInfo.getEndTime()+"&is_night_reserve=false&latitude=22.5333194732666&longitude=113.93041229248047&template_ids="+data+"&child_number=0";
            byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postDataBytes);
                wr.flush();
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                log.info("接口预约响应结果{}",response);
                GenerateOrderResponse generateOrderResponse = JSON.parseObject(response.toString(), GenerateOrderResponse.class);
                if(!Objects.isNull(generateOrderResponse)&&generateOrderResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                    return generateOrderResponse;
                }
                throw new RuntimeException("调用generateOrder接口预约失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
